package com.example.project.Controller;

import com.example.project.Service.BlogService;
import com.example.project.Service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private BlogService blogService;

    @PostMapping("/UpResource")
    public Map<String, Object> UpResource(@RequestParam("resource") MultipartFile files) {
        Map<String, Object> map = new HashMap<>();
        try{
            String url = resourceService.upLoadResource(files);
            if(url.equals("-2")){
                map.put("errno", "15001");
                map.put("message", "文件格式不正确！");
                return map;
            }
            if(url.equals("-1")){
                map.put("errno", "15002");
                map.put("message", "文件上传失败！");
                return map;
            }
            map.put("errno", "1");
            map.put("message", "文件上传成功！");
            map.put("result", url);
        } catch (Exception e){
            map.put("errno", "15002");
            map.put("message", "文件上传失败！");
        }
        return map;
    }

    @PostMapping("/DownResource")
    public Map<String, Object>DownLoadResource(@RequestBody Map<String, String> do_map){
        String blog_id = do_map.get("blog_id");
        Map<String, Object> map = new HashMap<>();
        try{
            blogService.addDownLoad(Integer.parseInt(blog_id));
            map.put("errno", "1");
            map.put("message", "下载成功！");
        } catch (Exception e){
            map.put("errno", "16001");
            map.put("message", "下载资源失败！");
        }
        return map;
    }
}
